const chromeMng = require('../mng/chromeMng')
const config = require('../util/config')
const logger = require('log4js').getLogger()

exports.start = () => {
  if (config.domain == '') {
    chromeMng.getJdBill().then(result => {
      exports.getJdBillResolve(result)
    }, result => {})
  } else if (config.domain == 'zoro.site') {
    var chromeServer = require('../mng/chromeServerMng').get()
    if (!chromeServer) {
      require('../mng/pushMng').push('no chrome servers')
      return
    }
    require('../util/getHtml')({
      url: chromeServer + 'getJdBill.do',
      data: JSON.stringify({})
    }).then(result => {
      var obj = JSON.parse(result)
      if (obj.result == 1) {
        exports.getJdBillResolve(obj.jdBill)
      } else {
        // logger.error('[' + __filename + ':' + __line + ']', result)
      }
    })
  }
}

exports.getJdBillResolve = result => {
  const mongoMng = require('../mng/mongoMng')
  if (!mongoMng.db) {
    return
  }
  result.forEach(item => {
    if (item.splitName == '已拆单' || item.validCodeStr == '无效-拆单' || item.validCodeStr == '无效-取消' || item.validCodeStr == '暂停') {
      return
    }
    mongoMng.db.collection('bill').find({
      orderId: item.orderId
    }).toArray((err, result) => {
      if (err) {
        log(err);
        return;
      }
      if (result.length == 0) {
        log('有新京东订单')
        mongoMng.db.collection('bill').insert([item], (err, result) => {
          if (err) {
            log(err);
            return;
          }
          require('../../task/handleBillTask').findCustomerForBill(item).then(result => {
            var instapush = require("instapush");
            instapush.settings({
              id: '5a4f9dbaa4c48a0efb7b23c6',
              secret: 'a8bcd4c4f871333053b060014d8f08ee',
            });
            instapush.notify({
              event: '有订单',
              trackers: {
                phone: result,
                mall: '京东'
              }
            }, (err, response) => {
              log(response);
            })
          })
        });
      } else {
        if (result[0].orderStatus != item.orderStatus && result[0].validCode != item.validCode) {
          log('京东订单[' + item.orderId + ']，原来状态：' + result[0].orderStatus + '、' + result[0].validCode + '，现在状态：' + item.orderStatus + '、' + item.validCode, item)
          require('../mng/pushMng').push('有京东订单状态更新')
        }
        mongoMng.db.collection('bill').update({
          orderId: item.orderId
        }, {
          $set: item
        }, (err, result) => {
          if (err) {
            log(err);
            return;
          }
        });
      }
    })
  })
}